package com.gztms.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Zoey
 * @date 2023/3/7 15:19
 * @Description
 **/
public class WebUtils {

    /**
     * 将字符串渲染到客户端
     * @param response 渲染对象
     * @param string    待渲染字符串
     * @return
     */
    public static String renderString(HttpServletResponse response, String string){

        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 配置响应头
     * @param filename
     * @param response
     * @throws UnsupportedEncodingException
     */
    public static void setDownloadHeader(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fname = URLEncoder.encode(filename,"UTF-8").replace("\\+","%20");
        response.setHeader("Content-disposition","attachment;filename="+fname);
    }

}
